package sample.tools;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import sample.SendRouterOrder.Router;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 百度地图坐标转换api
 * https://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition
 * 作者：w on 2021-08-24.
 * 邮箱：y141111@126.com
 * 版本：v1.0
 */
public class BMapChangePosition {
    private static final String Url1 = "https://api.map.baidu.com/geoconv/v1/?coords=";
    private static final String Url2 = "&from=1&to=5&ak=";
    private static final String AccessKey = "BC76a27687a33d846d9940a36844ccd7";  // 服务端秘钥

    /**
     * GPS坐标转换为百度地图坐标
     * 输入需转换的源坐标，多组坐标以“；”分隔（经度，纬度）
     * @param str GPS标准坐标（wgs84）；eg：114.21892734521,29.575429778924
     * @return 百度地图坐标
     */
    public static JSONArray changeGPSCoords(String str){
//    https://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.575429778924&from=1&to=5&ak=你的密钥 //GET请求
        JSONArray coords = null;
        BufferedReader br = null;
        try {
            URL url = new URL(Url1 + str + Url2+ AccessKey); // 设置请求地址
            URLConnection connectionData = url.openConnection();    // 打开和URL之间的连接
            // 设置通用的请求属性
            connectionData.setRequestProperty("accept", "*/*");
            connectionData.setRequestProperty("connection", "Keep-Alive");
            connectionData.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            connectionData.connect();   // 建立实际的连接
            Map<String, List<String>> map = connectionData.getHeaderFields();   // 获取所有响应头字段
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            connectionData.setConnectTimeout(1000);
            // 定义 BufferedReader输入流来读取URL的响应
            br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null)
                sb.append(line);
            String datas = sb.toString();
            JSONObject jsonObject = JSONObject.parseObject(datas);
            System.out.println(jsonObject);
            if (jsonObject.get("status").equals(0)){
                coords = (JSONArray) jsonObject.get("result");
            }
        }catch (Exception e){
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return coords;
    }
    public static void main(String[] args){
        StringBuilder coords = new StringBuilder();
        int i = 0;
        for (String[] item: Router.router3){
            coords.append(CoordinateTransformation.GPGGALatitude2GPS(Double.parseDouble(item[2])));
            coords.append(",");
            coords.append(CoordinateTransformation.GPGGALatitude2GPS(Double.parseDouble(item[1])));
            if (!item[0].equals(Router.router3[Router.router3.length -1][0])){
                coords.append(";");
            }
            i++;
        }
        JSONArray jsonArray = changeGPSCoords(coords.toString());
        System.out.println(jsonArray);
    }
}
